<template>
  <view class="appliance-header-bar">
    <view class="links">
      <slot v-if="showCustomSetting"></slot>
      <view v-if="showUsageReportIcon || hasGas" class="link" hover-class="hovering" @click="openUsageReport">
        <image mode="aspectFit" :src="'/static/nav/UsageReport.png'" />
        <text>
          {{ hasGas ? $t('Appliance.NavigateBar.GasReport.Text') : $t('Appliance.NavigateBar.UsageReport.Text') }}</text
        >
      </view>
      <view
        v-if="showShareButton"
        class="link"
        :class="{ disabled: isShareDisabled }"
        hover-class="hovering"
        @click="isVirtual ? shareVirtualAppliance() : shareAppliance()"
      >
        <image mode="aspectFit" :src="'/static/nav/Share.png'" />
        <text>{{ $t('Appliance.NavigateBar.Share.Text') }}</text>
      </view>
      <view
        v-if="showSettingIcon"
        class="link"
        hover-class="hovering"
        :class="{ 'has-dot': updateDetected }"
        @click="toApplianceSettings"
      >
        <image mode="aspectFit" :src="'/static/nav/Setting.png'" />
        <text>{{ $t('Appliance.NavigateBar.Setting.Text') }}</text>
      </view>
    </view>
  </view>
  <Modal
    open-type="share"
    :visible="shareShow"
    :title="$t('APP.Common.Tips.Text')"
    :description="$t('GotoShare.shareNoticeTips.Text')"
    :cancel-text="$t('APP.Common.Cancel.Text')"
    :ok-text="$t('APP.Common.Confirm.Text')"
    @ok="hideSharePop"
    @cancel="hideSharePop"
  />
  <VirtualShareNotice v-model:show="virtualShareNotice.show.value" />
  <!-- 请勿删除分享图片的cavans -->
  <canvas
    canvas-id="share-canvas"
    style="position: absolute; top: -1000px; left: -1000px; width: 225px; height: 180px"
  ></canvas>
</template>

<script setup lang="ts">
import Modal from '@/common/modal.vue'
import { TrackType, trackEvent } from '@/dataReport/tracks'
import type { BaseController } from '@/controller/BaseAppliance/definition'
import { actionDebounce, loadShareToken, showLoading, toPage } from '@/utils/mpHelper'
import { useAuthStore } from '@/store/auth'
import netconfig from '@/config/netconfig'
// import '@/pages/appliance/pluginHelper/pluginHelper'
import { useVirtualShareNotice } from '../Demo/utils'
import VirtualShareNotice from '../Demo/virtualShareNotice.vue'
import { useAccountStore } from '@/store/account'
import { safeTrack } from '@/dataReport/dataReportUtil'
import { useHeaderBarShare } from '@/utils/composition/useShare'
import { requestSubscribeUsingComplete } from '@/utils/mpHelper'

const authStore = useAuthStore()

const props = withDefaults(
  defineProps<{
    control: BaseController.Control
    showSettingIcon?: boolean
    showShareIcon?: boolean
    checkUpdate?: boolean
    shareDisabled?: boolean // 是否置灰分享按钮
    hasGas?: boolean
    showCustomSetting?: boolean
  }>(),
  {
    showSettingIcon: true,
    showShareIcon: true,
  }
)
const emit = defineEmits<{
  (e: 'open-usage-report'): void
  (e: 'share'): void
  (e: 'to-settings'): void
}>()

const haId = computed(() => props.control.store._datasource.haId)
const vib = computed(() => props.control.store._datasource.vib)
const type = computed(() => props.control.store._datasource.type)
const guest = computed(() => props.control?.store.detail?.guest)
const name = computed(() => props.control?.store.detail?.name || '')
const connected = computed(() => props.control.store.detail?.connected)
const remoteControl = computed(() => props.control.store.remoteControl)
const remoteStart = computed(() => props.control.store.remoteStart)

const showUsageReportIcon = computed(() => props.control.store.detail?.usageReport)
const showShareButton = computed(() => !props.control.store.detail?.guest && props.showShareIcon)

const isVirtual = computed(() => props.control.store.isVirtualAppliance)
const isShareDisabled = computed(() => {
  if (isVirtual.value) return false
  return props.shareDisabled
})
let requestIngFlag = false
/**
 * 分享家电
 */
useHeaderBarShare({
  vib,
  name,
  type,
})

const updateDetected = computed(() => props.control.store.updateDetected && props.control.store.isOffline !== true)

/**
 * 点击用户使用报告
 */
function openUsageReport() {
  let trackKey = props.hasGas ? 'Appliance.NavigateBar.GasReport.Text' : 'Appliance.NavigateBar.UsageReport.Text'
  trackEvent(trackKey, {}, TrackType.ApplianceDetail)

  if (!props.hasGas) {
    gotoUsageReportPlugin()
  }
  emit('open-usage-report')
}

/**
 * 点击分享家电
 */
const shareShow = ref(false)
const virtualShareNotice = useVirtualShareNotice()
const accountStore = useAccountStore()

function shareVirtualAppliance() {
  virtualShareNotice.open()
}

const shareAppliance = actionDebounce({
  delay: 3000,
  call: async () => {
    await loadShareToken(haId.value, type.value)
    if (accountStore.sharetoken) {
      shareShow.value = true
    } else {
      uni.showToast({
        title: '获取shareToken失败',
        icon: 'error',
        duration: 3000,
      })
    }

    emit('share')
  },
})

function hideSharePop() {
  shareShow.value = false
  safeTrack(() => {
    trackEvent('share_appliance', {}, TrackType.ApplianceDetail, 'Appliance.Deail.Share.Appliance')
  })
}

/**
 * 跳转家电设置页
 */
async function toApplianceSettings() {
  // 防止快速点击出现重复请求和 跳转
  if (requestIngFlag) {
    return
  }
  requestIngFlag = true
  safeTrack(() => {
    trackEvent('Appliance.NavigateBar.Setting.Icon', {}, TrackType.ApplianceDetail)
  })
  if (!isVirtual.value) {
    // 一次性消息订阅
    await requestSubscribeUsingComplete([netconfig.DeviceStateId])
  }
  await toApplianceSettingPage()
  requestIngFlag = false
}
const toApplianceSettingPage = actionDebounce({
  delay: 1000,
  call: async () => {
    emit('to-settings')
    let pageUrl = '/pages/appliance/settings/applianceSettings'
    if (isVirtual.value) {
      pageUrl = '/pages/appliance/Demo/settings/applianceSettings'
    }
    return toPage(pageUrl, {
      haId: haId.value,
      vib: vib.value,
      type: type.value,
      guest: guest.value,
      connected: connected.value,
      remoteControl: remoteControl.value,
      remoteStart: remoteStart.value,
      isVirtual: isVirtual.value,
      name: name.value,
    })
  },
})

/**
 * 跳转用户使用报告
 */
const gotoUsageReportPlugin = actionDebounce({
  delay: 3000,
  call: () =>
    showLoading(() => {
      return new Promise<void>((resolve, reject) => {
        requirePlugin(
          'demo-plugin',
          async (demoPlugin) => {
            try {
              demoPlugin.initEnv(netconfig.PLUGIN_ENV, authStore.accessToken, '', netconfig.APPID)
              let reportParams = null
              // 虚拟家电 插件参数
              if (isVirtual.value) {
                reportParams = {
                  virtualType: type.value,
                  subType: 'HC3.0',
                }
              }
              // 真实家电 插件参数
              else {
                reportParams = {
                  haid: haId.value,
                  subType: 'HC3.0',
                }
              }
              await toPage('plugin://demo-plugin/userReportHC3_0', reportParams)
              resolve()
            } catch (e) {
              reject(e)
            }
          },
          (e) => {
            reject(e)
            uni.hideLoading()
            uni.showToast({
              title: '加载异常，请稍后再试',
              icon: 'none',
            })
          }
        )
      })
    }),
})
</script>

<style lang="less">
.appliance-header-bar {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  .disabled {
    opacity: 0.6;
    pointer-events: none;
  }
  .links {
    display: flex;
    flex-flow: row nowrap;
    margin-right: 40rpx;
  }
  .link {
    display: flex;
    flex-flow: column nowrap;
    justify-content: center;
    align-items: center;
    color: var(--dark-color);
    &.hovering {
      opacity: 0.8;
    }
    &.has-dot {
      position: relative;
      &::after {
        content: '';
        display: block;
        position: absolute;
        top: -4rpx;
        right: -4rpx;
        width: 8rpx;
        height: 8rpx;
        border-radius: 50%;
        background-color: var(--danger-color);
      }
    }
    > image {
      width: 40rpx;
      height: 40rpx;
    }
    > text {
      display: block;
      margin-top: 4rpx;
      font-size: 20rpx;
      font-weight: 400;
      line-height: 24rpx;
    }
  }
  .link + .link {
    margin-left: 40rpx;
  }
  .nav-link {
    color: #131314;
  }
}
</style>
